package com.acme.service.bank;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.util.StringTokenizer;

import com.acme.domain.account.Account;
import com.acme.domain.account.CheckingAccount;
import com.acme.domain.account.SavingAccount;
import com.acme.domain.bank.Bank;
import com.acme.domain.bank.Client;
import com.acme.domain.bank.Gender;

public class BankDataLoader implements Serializable {
	private BankService bankService;
	private String accType;
	private String clientName;
	private Gender gender;
	private double balance;
	private double overdraft;
	private int clientId;

	/**
	 * Loads a file which contains data feed in the following format: <br>
	 * accounttype=c|s;balance=100;overdraft=50;name=John;gender=m|f;
	 * 
	 * @param bank
	 * @param path
	 * @throws FileNotFoundException
	 */
	public void load(final Bank bank, final String path)
			throws FileNotFoundException, ClassNotFoundException, IOException {

		BufferedReader in = new BufferedReader(new FileReader(path));
		StringBuffer sb = new StringBuffer();
		String s;
		while ((s = in.readLine()) != null) {
			StringTokenizer st = new StringTokenizer(s, "=;");
			clientId++;
			while (st.hasMoreTokens()) {
				String key = st.nextToken();
				if (key.equals("accounttype")) {
					if (st.nextToken().equals("c")) {
						accType = "checking";
					} else {
						accType = "saving";
					}

				}

				if (key.equals("balance")) {
					balance = Double.parseDouble(st.nextToken());
				}

				if (key.equals("overdraft")) {
					overdraft = Double.parseDouble(st.nextToken());
				}
				if (key.equals("name")) {
					clientName = st.nextToken();
				}
				if (key.equals("gender")) {
					if (st.nextToken().equals("m")) {
						gender = Gender.MALE;
					} else {
						gender = Gender.FEMALE;
					}
				}

			}
			Client client = new Client(clientName, gender);
			Account clientAcc = null;
			if (accType.equals("checking")) {
				clientAcc = new CheckingAccount(clientId, balance, overdraft);
			} else {
				clientAcc = new SavingAccount(clientId, balance);
			}

			bank.addClient(client);
			client.addAccount(clientAcc);
		}
		in.close();

	}

	public BankService getBankService() {
		return bankService;
	}

	public void setBankService(final BankService bankService) {
		this.bankService = bankService;
	}
}
